package com.hmall.common.config;

import com.hmall.common.utils.UserContext;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnClass({MessageConverter.class, RabbitTemplate.class})
public class MqConfig {

    @Bean
    @ConditionalOnClass
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory, MessageConverter messageConverter) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(messageConverter);
        rabbitTemplate.setBeforePublishPostProcessors(message ->  {
            message.getMessageProperties().setHeader("user-info", UserContext.getUser());
            return message;
        });
        return rabbitTemplate;
    }

//    @Bean
//    public SimpleMessageListenerContainer messageListenerContainer(
//            ConnectionFactory connectionFactory,
//            MessageConverter messageConverter) {
//
//        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
//        container.setQueueNames("cart.clear.queue");
//
//        container.setAfterReceivePostProcessors(message -> {
//            // 从消息头中获取用户信息并设置到用户上下文中
//            Object userInfo = message.getMessageProperties().getHeaders().get("user-info");
//            if (userInfo != null) {
//            UserContext.setUser(Long.valueOf(userInfo.toString()));
//            }
//            return message;
//        });
//
//        return container;
//    }


}